package com.culture.config.core;

import java.util.HashMap;
import java.util.Map;

import javax.annotation.PostConstruct;

import org.apache.commons.collections.MapUtils;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.MediaType;
import org.springframework.web.servlet.config.annotation.ContentNegotiationConfigurer;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;

import com.culture.config.common.interceptor.SessionInterceptor;

import lombok.extern.slf4j.Slf4j;

@Slf4j
@Configuration
public class WebConfig extends WebMvcConfigurationSupport{
	
	@PostConstruct
    public void initWebConfig(){
		 log.info("WebConfig initialized");
	}
	
	@Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new SessionInterceptor()).addPathPatterns("/api/config/**"); //not system level ,is business self
    }

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {       
        Map<String,String> resourceMap = this.loadStaticResourceMap();
        if(MapUtils.isEmpty(resourceMap)) {
        	return;
        }
        resourceMap.forEach((k,v)->{
        	 registry.addResourceHandler(k).addResourceLocations(v);
        	 log.info("WebConfig add ResourceHandlers:[{},{}]",k, v);  
        });       
    }

    @Override
    public void configureContentNegotiation(ContentNegotiationConfigurer configurer) {
        configurer.defaultContentType(MediaType.APPLICATION_JSON);
    }    

    private Map<String,String> loadStaticResourceMap(){
    	Map<String,String> resourceMap = new HashMap<>();    	
    	resourceMap.put("/static/**", "classpath:/META-INF/resources/static");
        resourceMap.put("/assets/**", "classpath:/META-INF/resources/assets");
    	resourceMap.put("/webjars/**", "classpath:/META-INF/resources/webjars/"); 
    	return resourceMap;
    }
}
